package com.lmxdawn.api.dnf.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmxdawn.api.common.session.SessionContextHolder;
import com.lmxdawn.api.common.session.SessionHelper;
import com.lmxdawn.api.common.session.TokenHelper;
import com.lmxdawn.api.dnf.entity.RealName;
import com.lmxdawn.api.dnf.mapper.RealnameMapper;
import com.lmxdawn.api.dnf.service.IRealnameService;
import com.lmxdawn.api.dnf.util.AuthUtil;
import lombok.val;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RealnameServiceImpl  extends ServiceImpl<RealnameMapper, RealName>  implements IRealnameService {
    @Value("${auth.appCode:}")
    private String appCode;
    @Resource
    private RedissonClient redissonClient;
    @Override
    public boolean auth(String realname, String idNo, String id){
        val lock = redissonClient.getLock(String.format("REALNAME:%s", id));
        if (!lock.tryLock()){
            throw new RuntimeException("系统繁忙，请稍后");
        }
        try {
            List<RealName> list = this.lambdaQuery().eq(RealName::getUserId, id).list();
            boolean res = AuthUtil.authCheck(appCode, realname, idNo);
            RealName r = new RealName();
            if (CollUtil.isNotEmpty(list)){
                r = list.get(0);
            }
            r.setRealname(realname);
            r.setIdNo(idNo);
            r.setUserId(id);
            r.setStatus(res ? 1 : 0);
            this.saveOrUpdate(r);
            return res;
        }catch (Exception e){
            return false;
        }finally {
            lock.unlock();
        }
    }
}
